package com.sirui.x.learnIo.nioV2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerSocketChannelWrapperV2 {
	
	private static final Logger log = LoggerFactory.getLogger(ServerSocketChannelWrapperV2.class);
    
    public static final int LISTEN_PORT = 4010;

    /**
     *  ServerSocketChannel#configureBlocking 为true表示ServerSocketChannel#accpet()堵塞，false为非堵塞；
     * 
     *  SocketChannel#configureBlocking 为true表示SocketChannel#read()堵塞，false为非堵塞；
     *  
     *  上述两个为true，则NIO 实现方式和 BIO 一样；若为false则是异步非堵塞，一般使用selector反映着模式
     */
    public void startAndListen() throws Exception {
		ServerSocketChannel ssChannel = ServerSocketChannel.open();
        ssChannel.bind(new InetSocketAddress(LISTEN_PORT));

//        Selector selector = Selector.open();
        //ServerSocketChannel#accpet() true为堵塞，false为非堵塞；
//        ssChannel.configureBlocking(false);
        //注册selector必须使用非堵塞的ServerSocketChannel
//      ssChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        while (true) {
        	log.info("server nio start.");
        	SocketChannel socketChannel = ssChannel.accept();
        	if(socketChannel != null) {
        		log.info("accept channle");
//        		socketChannel.configureBlocking(false); //默认true
        		new Thread(() -> {
        			try {
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						while(true) {
							int len = socketChannel.read(buffer);
							log.info("read: {}", new String(buffer.array(), 0, len));
							buffer.clear();
						}
					} catch (IOException e) {
						log.error("", e);
					}
        		}).start();
        	}else {
        		Thread.sleep(500);
        	}
		}

	}
    

    public static void main(String[] args) throws Exception {
        new ServerSocketChannelWrapperV2().startAndListen();
    }
}
